package jpa.controller;

import jpa.entity.Account;
import jpa.entity.Person;
import jpa.repository.AccountRepository;
import jpa.repository.PersonRepository;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by barton on 16-5-13.
 */
@Controller
@RequestMapping("/persons")
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private AccountRepository accountRepository;

    /**
     * 仅用来测试结合shiro做审计功能
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public HttpEntity<Person> save() {

        // 添加一个用于登陆的用户
        Account existsAccount = accountRepository.findByUsername("barton");

        if (null == existsAccount) {
            Account loginAccount = new Account();
            loginAccount.setUsername("barton");
            loginAccount.setPassword("barton_password");
            accountRepository.save(loginAccount);
        }

        // 使用shiro进行登陆
        UsernamePasswordToken token = new UsernamePasswordToken("barton", "barton_password");

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
            System.out.println("登陆成功!");
        } catch (UnknownAccountException ex) {
            System.out.println("用户不存在");
        } catch (IncorrectCredentialsException ex) {
            System.out.println("用户密码不正确");
        }

        Person person = new Person();
        person.setFirstName("firstname");
        person.setLastName("lastname");

        personRepository.save(person);

        return new ResponseEntity<>(person, HttpStatus.CREATED);
    }
}
